<!DOCTYPE html>
<html lang="en">
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>个人中心</title>
    <link rel="shortcut icon" href="../static/favicon.ico" />
    <link rel="bookmark" href="/favicon.ico" />
    <link rel="stylesheet" type="text/css" href="../static/css/base.css">
    <link rel="stylesheet" type="text/css" href="../static/css/admin.css">
    <link rel="stylesheet" type="text/css" href="../static/css/jquery.dataTables.min.css">
    <script type="text/javascript" src="../static/js/jquery-3.3.1.min.js"></script>
    <script type="text/javascript" src="../static/js/base.js"></script>
    <script type="text/javascript" src="../static/js/jquery.dataTables.min.js"></script>
    <script type="text/javascript">
        var ele; //保存图片对象
        var flag = 0; //图片是否修改
        // 图片上传
        function imgPreview(fileDom, element) {
            //判断是否支持FileReader
            if (window.FileReader) {
                var reader = new FileReader();
            } else {
                alert("您的设备不支持图片预览功能，如需该功能请升级您的设备！");
            }
            //获取文件
            var file = fileDom.files[0];
            var imageType = /^image\//;
            //是否是图片
            if (!imageType.test(file.type)) {
                alert("请选择图片！");
                return;
            }
            //读取完成
            reader.onload = function(e) {
                //获取图片dom
                ele = e;
                var img = document.getElementById(element);
                //图片路径设置为读取的图片
                img.src = e.target.result;
                flag = 1;
            };
            reader.readAsDataURL(file);

        }
    </script>
</head>

<body>
    <header>
        <div class="container clearfix" id="top">
            <a href="/index"><img class="logo" src="../static/img/logo.png"></a>
            <a class="topbar-item" href="/index">首页</a>
            <a class="topbar-item" href="/category">小吃分类</a>
            <span th:if="${session.user} != null">
            <a class="topbar-item" href="/my" th:if="${session.user.username!='admin'}">个人中心</a>
            <a class="topbar-item  active" href="/admin" th:if="${session.user.username=='admin'}">个人中心</a>
            </span>
            <nav th:if="${session.user} == null">
                <a href="/register">注册</a>
                <span>|</span>
                <a href="/login">登录</a>
            </nav>
            <nav th:if="${session.user} != null">
                您好！<span th:text="${session.user.getUsername()}"></span>，<a href="/loginOut">退出</a>
            </nav>
        </div>
    </header>
    <a id="toTop" title="回到顶部"><img src="../static/img/scroll_top1.png"></a>
    <div class="main-box">
        <div class="merchant">
            <div class="tabs fl">
                <ul>
                    <li class="myactive"><img src="../static/img/shenhe.png" alt="">小吃审核</li>
                    <li><img src="../static/img/fenlei.png">分类设置</li>
                    <li><img src="../static/img/xinxi.png">信息管理</li>
                </ul>
            </div>
            <div class="tabs-content clearfix">
                <div class="my_order">
                    <table id="noPassTable" border="1" class="table table-striped table-bordered">
                        <thead>
                            <tr>
                                <th>小吃ID</th>
                                <th>小吃名称</th>
                                <th>小吃图片</th>
                                <th>小吃分类</th>
                                <th>小吃简介</th>
                                <th>提交时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
                <div class="shop_setting hide">
                    <div class="setting-item">
                        <h1>小吃分类</h1>
                        <table id="categoryTable" border="1">
                            <tr>
                                <th>分类名称</th>
                                <th>操作</th>
                            </tr>
                            <tr th:each="category:${categorys}">
                                <td th:text="${category.getCategoryName()}"></td>
                                <td th:text="${category.getId()}" class="hide"></td>
                                <td><button class="edit_category">编辑</button><button class="delete_category">删除</button></td>
                            </tr>
                            <tr>
                        </table>
                    </div>
                    <div class="btn">
                        <button id="add_category">添加分类</button>
                    </div>
                </div>
                <div class="goods_setting hide">
                    <div class="btn"><button id="add_goods">添加小吃</button></div>
                    <table id="passTable" border="1" class="table table-striped table-bordered">
                        <thead>
                            <tr>
                                <th>小吃ID</th>
                                <th>小吃名称</th>
                                <th>小吃图片</th>
                                <th>小吃简介</th>
                                <th>小吃分类</th>
                                <th>创建时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
                <div id="editCategory" class="hide">
                    <div class="close">
                        <button class="close_btn"></button>
                    </div>
                    <div class="pop_content">
                        <h2>小吃分类</h2>
                        <div class="edit_item">
                            <span>分类名称</span>(最大长度15)
                            <input type="text" name="" maxlength="15">
                        </div>
                    </div>
                    <button class="edit_save" id="category_save">保存</button>
                </div>
                <div id="editGoods" class="hide">
                    <div class="close">
                        <button class="close_btn"></button>
                    </div>
                    <div class="pop_content">
                        <h2>小吃详情</h2>
                        <div class="edit_item">
                            <span>小吃名称</span>(最大长度15)
                            <input placeholder="请输入小吃名称" type="text" name="" maxlength="15">
                        </div>
                        <div class="edit_item">
                            <span>小吃图片</span>
                            <img id='edit_preview' src="../static/img/demo.png">
                            <input type="file" name="file" id="imgFile" onchange="imgPreview(this,'edit_preview')">
                        </div>
                        <div class="edit_item">
                            <span>小吃分类</span>
                            <select>
                                <option>请选择小吃分类</option>
                                <option th:each="category:${categorys}" th:text="${category.getCategoryName()}"></option>
                            </select>
                        </div>
                        <div class="edit_item">
                            <span>小吃简介</span>
                            <textarea placeholder="请输入小吃简介" maxlength="300"></textarea>
                            <i class="tip"><span id="intro_count">0</span>/300</i>
                        </div>
                    </div>
                    <button class="edit_save" id="goods_save">保存</button>
                </div>
            </div>
        </div>
        <div id="mask" class="hide"></div>
    </div>
    <script th:inline="javascript">
        var BaseUrl = '[(${BaseUrl})]';
    $(function() {
        var getIndexNum = sessionStorage.getItem("tabLiNum");
        $(".tabs li").eq(getIndexNum).addClass('myactive').siblings().removeClass('myactive');
        console.log($(".tabs-content div").eq(getIndexNum))
        $(".tabs-content>div").eq(getIndexNum).removeClass("hide").siblings(".tabs-content>div").addClass("hide");


        noPassTable();
        passTable();
        function timestampTodate(obj){
            var newDate = new Date();
            newDate.setTime(obj);
            return newDate.toLocaleString();
        }
        function noPassTable(){
            var table = $('#noPassTable').DataTable({
                destroy: true,
                "lengthChange": false,
                "processing": true,
                "deferRender": true,
                "autoWidth":false,
                "pageLength": 5,
                ajax: {
                    url: BaseUrl+"getNopassFood"
                },
                columns: [
                    { data: 'id' },
                    { data: 'name' },
                    { data: 'foodImg',render:function (data,type,full,meta) {
                            return "<img src="+data+">"
                        } },
                    { data: 'category' },
                    { data: 'intro',render:function (data,type,full,meta) {
                            return "<textarea disabled>"+data+"</textarea>";
                        }},
                    { data: 'createTime',render:function (data,type,full,meta) {
                            var newtime = timestampTodate(data)
                            return newtime;
                        } }
                ],
                columnDefs: [
                    {
                        targets: 6,
                        render: function (data,type, full, meta) {
                            return "<button class=\"order_btn\">通过审核</button>";
                        }
                    }

                ],
                "language": {
                    "lengthMenu": "_MENU_ 条记录每页",
                    "zeroRecords": "没有找到记录",
                    "info": "第 _PAGE_ 页 ( 总共 _PAGES_ 页 )",
                    "infoEmpty": "无记录",
                    "infoFiltered": "(从 _MAX_ 条记录过滤)",
                    "paginate": {
                        "previous": "上一页",
                        "next": "下一页"
                    }
                },
            });
            table.order([5,'dsc']).draw();
        }

        function passTable(){
           var table1 = $('#passTable').DataTable({
                destroy: true,
                "lengthChange": false,
                "processing": true,
                "deferRender": true,
                "pageLength": 5,
                "autoWidth":false,
                ajax: {
                    url: BaseUrl+"getPassFood"
                },
                columns: [
                    { data: 'id' },
                    { data: 'name' },
                    { data: 'foodImg',render:function (data,type,full,meta) {
                            return "<img src="+data+">"
                        } },
                    { data: 'intro',render:function (data,type,full,meta) {
                            return "<textarea disabled>"+data+"</textarea>";
                        }},
                    { data: 'category' },
                    { data: 'createTime',render:function (data,type,full,meta) {
                            var newtime = timestampTodate(data)
                            return newtime;
                        } }

                ],
                columnDefs: [
                    {
                        targets: 6,
                        render: function (data,type, full, meta) {
                            return "<button class='edit_goods'>编辑</button><button class='delete_goods'>删除</button>";
                        }
                    }

                ],
                "language": {
                    "zeroRecords": "没有找到记录",
                    "info": "第 _PAGE_ 页 ( 总共 _PAGES_ 页 )",
                    "infoEmpty": "无记录",
                    "infoFiltered": "(从 _MAX_ 条记录过滤)",
                    "paginate": {
                        "previous": "上一页",
                        "next": "下一页"
                    }
                },
            });
            table1.order([5,'dsc']).draw();
        }
        //审核通过
        function confirmPass(obj, id) {
            var message = confirm("确认通过？");
            if (message == true) {
                console.log(id);
                var data={
                    "id":id
                }
                $.ajax({
                    url:"goPass",
                    type:"post",
                    data:data,
                    success:function (data) {
                        if(data=="success"){
                            alert("操作成功！")
                            noPassTable();
                            passTable();
                        }
                    },
                    error:function (err) {
                        alert("操作失败！");
                    }

                })
            }
        }
        $("#noPassTable").on("click",'.order_btn',function () {
            var id = $(this).parent().parent().find("td").eq(0).text();
            confirmPass(this, id);
        })


        //分类删除
        function confirmDelete(obj) {
            var message = confirm("确认删除？");
            var id = $(obj).parent().parent().find('td').eq(1).text();
            if (message == true) {
                //数据库删除操作
                var data={
                    "id":id
                }
                $.ajax({
                    url:"/deleteCategory",
                    data:data,
                    type:"post",
                    success:function (data) {
                        if(data=="success"){
                            alert("删除成功！")
                            $(obj).parent().parent().remove();
                            window.location.reload()
                        }
                    },
                    error:function (err) {
                        alert("删除失败！有其他小吃归属该分类！");
                    }
                })
            }
        }
        $("#categoryTable").on("click", ".delete_category", function() {
            confirmDelete(this);
        })



        //编辑分类
        $("#categoryTable").on("click", ".edit_category", function() {
            var oText = $(this).parent().parent().find('td').eq(0).text();
            $('#editCategory').find('.edit_item input').val(oText);
            $('#editCategory,#mask').removeClass('hide')
            var index = $(this).parent().parent().index();
            var id=$(this).parent().parent().find('td').eq(1).text();
            $('#category_save').unbind("click").on("click", function() {

                var value = $('#editCategory').find('.edit_item input').val();
                if (value != oText) {
                    // 数据库更新操作
                    var data={
                        "id":id,
                        "name":value
                    }
                    $.ajax({
                        url:"/editCategory",
                        data:data,
                        type:"post",
                        success:function (data) {
                            if(data=="success"){
                                alert("修改成功！")
                                window.location.reload()
                            }
                        },
                        error:function (err) {
                            alert("修改失败！");
                        }
                    })
                }
                $("#categoryTable").find("tr").eq(index).find("td").eq(0).html(value)
                $('#editCategory,#mask').addClass('hide')
            })
        })
        // 增加小吃分类
        $('#add_category').click(function() {
            $('#editCategory .pop_content .edit_item input').val("");
            $('#editCategory,#mask').removeClass('hide')
            $("#category_save").unbind("click").on("click", function() {
                var value = $('#editCategory').find('.edit_item input').val();
                // 数据库增加操作
                var data={
                    "name":value
                }
                $.ajax({
                    url:"/insertCategory",
                    data:data,
                    type:"post",
                    success:function (data) {
                        if(data=="success"){
                            alert("增加成功！")
                            window.location.reload()
                        }
                    },
                    error:function (err) {
                        alert("增加失败！");
                    }
                })
                $("#categoryTable").append("<tr><td>" + value + "</td><td><button class='edit_category'>编辑</button><button class='delete_category'>删除</button></td></tr>");
                $('#editCategory,#mask').addClass('hide')
            })
        })






        //增加小吃信息
        $('#add_goods').click(function() {
            $('#editGoods').find('.edit_item input').eq(0).val("");
            $('#editGoods').find('.edit_item img').attr('src', "");
            $('#editGoods').find('.edit_item input').eq(1)[0].value="";
            $('#editGoods').find('.edit_item textarea').val("");
            $('#editGoods').find('.edit_item select').val("请选择小吃分类");
            $("#intro_count")[0].innerHTML = 0
            $('#editGoods,#mask').removeClass('hide')
            $(".edit_save").unbind("click").on("click", function() {
                var name = $('#editGoods').find('.edit_item input').eq(0).val();
                var img = $('#imgFile')[0].files[0];
                var intro = $('#editGoods').find('.edit_item textarea').val();
                var category = $('#editGoods').find('.edit_item select option:selected').text();
                if(name==undefined||img==undefined||category=="请选择小吃分类"||intro==""){
                    alert("请将信息填写完整")
                }else{
                    var msg = confirm("确认保存？");
                    if(msg==true){
                        var formData=new FormData();
                        formData.append("name",name);
                        formData.append("img",img);
                        formData.append("intro",intro);
                        formData.append("category",category);
                        formData.append("status","1");
                        $.ajax({
                            url:"/insertFood",
                            data:formData,
                            type:"post",
                            cache: false,
                            processData: false,
                            contentType: false,
                            success:function (data) {
                                if(data=="success"){
                                    alert("增加成功！")
                                    passTable();
                                }
                            },
                            error:function (err) {
                                alert("增加失败！");
                            }
                        })
                        $('#editGoods,#mask').addClass('hide')
                    }
                }
 
            })
        })

        //编辑小吃信息
        $(".goods_setting").on("click", ".edit_goods", function() {
            var id = $(this).parent().parent().find('td').eq(0).text();
            $('#editGoods').find('.edit_item input').eq(0).val($(this).parent().parent().find('td').eq(1).text());
            $('#editGoods').find('.edit_item img').attr('src', $(this).parent().parent().find('img').attr('src'))
            $('#editGoods').find('.edit_item input').eq(1)[0].value="";
            $('#editGoods').find('.edit_item textarea').val($(this).parent().parent().find('td').eq(3).text());
            $('#editGoods').find('.edit_item select').val($(this).parent().parent().find('td').eq(4).text())
            $('#editGoods,#mask').removeClass('hide')
            $("#intro_count")[0].innerHTML = $('#editGoods').find('.edit_item textarea').val().length
            $(".edit_save").unbind("click").on("click", function() {
                var formData = new FormData();
                var name = $('#editGoods').find('.edit_item input').eq(0).val();
                if($('#editGoods').find('.edit_item input').eq(1)[0].value!=""){
                    var img = $('#imgFile')[0].files[0];
                    formData.append("img",img);
                    console.log("img"+img);
                }
                var intro = $('#editGoods').find('.edit_item textarea').val();
                var category = $('#editGoods').find('.edit_item select option:selected').text();
                console.log("id"+id)
                console.log("name"+name)
                console.log("intro"+intro);
                console.log("category"+category);
                if(name==""||category=="请选择小吃分类"||intro==""){
                    alert("请将信息填写完整")
                }else{
                    var msg = confirm("确认保存？");
                    if(msg==true) {
                        formData.append("name", name);
                        formData.append("intro", intro);
                        formData.append("category", category);
                        formData.append("id", id);
                        $.ajax({
                            url: "/updateFood",
                            data: formData,
                            type: "post",
                            cache: false,
                            processData: false,
                            contentType: false,
                            success: function (data) {
                                if (data == "success") {
                                    alert("修改成功！")
                                    window.location.reload();
                                }
                            },
                            error: function (err) {
                                alert("修改失败！");
                            }
                        })
                        $('#editGoods,#mask').addClass('hide')
                    }
                }
            })
        })
        function confirmDeleteGoods(obj,id){
            var message = confirm("确认删除？");
            if (message == true) {
                var data={
                    "id":id
                }
                $.ajax({
                    url:"/deleteFood",
                    data:data,
                    type:"post",
                    success:function (data) {
                        if(data=="success"){
                            alert("删除成功！")
                            passTable();
                        }
                    },
                    error:function (err) {
                        alert("删除失败！");
                    }
                })
            }
        }
        //删除小吃信息
        $("#passTable").on("click",".delete_goods",function () {
            var id=$(this).parent().parent().find("td").eq(0).text();
            confirmDeleteGoods(this,id);
        })


        //tab栏切换
        $('.merchant .tabs ul li').click(function() {
            $(this).addClass('myactive');
            $(this).siblings().removeClass('myactive');
            if ($(this).index() == 0) {
                $('.my_order').removeClass('hide');
                $('.shop_setting,.goods_setting').addClass('hide');
            } else if ($(this).index() == 1) {
                $('.shop_setting').removeClass('hide');
                $('.goods_setting,.my_order').addClass('hide');
            } else if ($(this).index() == 2) {
                $('.goods_setting').removeClass('hide');
                $('.my_order,.shop_setting').addClass('hide');
            }
            var indexNum = $(this).index(); //所点击li的索引值
            console.log("当前li的下标为：",indexNum); //打印索引值
            sessionStorage.setItem("tabLiNum",indexNum); //将(下标名称，索引值)存入session中
        })



        // 弹出窗口
        $('.close').click(function() {
            $(this).parent().addClass('hide');
            $('#mask').addClass('hide')
        })
        //文本框字数获取
        $("textarea").on("input", function() {
            $("#intro_count")[0].innerHTML = $(this).val().length
        })
    })
    </script>
</body>

</html>